package microservice.registory;


import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @program: rocsun
 * @description: http心跳
 * @author: yx.guo
 * @create: 2025-08-07 21:37
 **/
public class HttpHeartbeat {
    private final String serverUrl;
    // 时间间隔
    private final long interval;
    // 调度器
    private final ScheduledExecutorService scheduler;
    // 失败充实次数
    private int failedAttempts = 0;
    // 最大失败重试次数
    private final int maxFailedAttempts;

    public HttpHeartbeat(String serverUrl, long intervalSeconds, int maxFailedAttempts) {
        this.serverUrl = serverUrl;
        this.interval = intervalSeconds;
        this.maxFailedAttempts = maxFailedAttempts;
        this.scheduler = Executors.newSingleThreadScheduledExecutor();
    }

    /**
     * 启动任务调度
     */
    public void start() {
        scheduler.scheduleAtFixedRate(this::sendHeartbeat, 0, interval, TimeUnit.SECONDS);
    }


    /**
     * 发送心跳
     */
    private void sendHeartbeat() {
        try {
            URL url = new URL(serverUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("HEAD");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);

            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                failedAttempts = 0;
                System.out.println("Heartbeat successful");
            } else {
                handleFailure();
            }
        } catch (Exception e) {
            handleFailure();
        }
    }

    /**
     * 处理失败的情况
     */
    private void handleFailure() {
        failedAttempts++; // 失败重试次数+1
        System.out.println("Heartbeat failed. Attempt " + failedAttempts + "/" + maxFailedAttempts);

        // 如果重试次数足够，那么关闭任务调度线程池
        if (failedAttempts >= maxFailedAttempts) {
            System.err.println("Max failed attempts reached. Service unavailable.");
            // 可以触发重连或其他恢复逻辑
            scheduler.shutdown();
        }
    }

    public static void main(String[] args) {
        HttpHeartbeat heartbeat = new HttpHeartbeat("http://example.com/health", 10, 3);
        heartbeat.start();
    }
}
